package com.joelaws.prototype.server.dao;

import gnu.trove.THashMap;
import gnu.trove.TLongObjectHashMap;

import java.util.List;

import com.joelaws.prototype.client.data.User;
import com.joelaws.prototype.client.util.Create;

public class UserDAO {

	private static synchronized long getNextID() {
		return ++currentID;
	}

	private static long currentID = 0;

	private THashMap<String, User> userEmailCache;

	private TLongObjectHashMap<User> userIDCache;

	protected UserDAO() {
		userEmailCache = new THashMap<String, User>();
		userIDCache = new TLongObjectHashMap<User>();
	}

	public synchronized List<User> getUsers(boolean getFemales) {
		List<User> clones = Create.newList();
		for (User user : userEmailCache.values()) {
			if (user.getNetworkingService() != null && user.getNetworkingDetails() != null
					&& getFemales != user.isMale()) {
				clones.add(user.clone());
			}
		}
		return clones;
	}

	public synchronized User getUser(long userID) {
		return userIDCache.get(userID).clone();
	}

	public synchronized User getUser(String email, String password) {
		User user = userEmailCache.get(email);

		if (user != null && user.getPassword().equals(password)) {
			user = user.clone();
		} else {
			user = null;
		}
		return user;
	}

	public synchronized void storeUser(User user) {
		if (user.getUserID() == 0) {
			user.setUserID(getNextID());
		}
		userEmailCache.put(user.getEmail(), user);
		userIDCache.put(user.getUserID(), user);
	}

}
